package org.example.juc.lock;

import lombok.extern.slf4j.Slf4j;
import org.example.juc.lock.clh.CLHLock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义可重入锁
 */
@Slf4j
public class SpinLock implements Lock {

    public static int counter = 0;

    /**
     * 定义好状态：有锁的时候是什么样子的，无锁的状态是什么
     * 锁住的时候，currThread.get() == 当前锁
     * 释放锁的时候，currThread是空
     */
    private AtomicReference<Thread> currThread = new AtomicReference<>();

    /**
     * 可重入次数
     */
    private int count = 0;

    @Override
    public void lock() {
        Thread thread = Thread.currentThread();
        if (thread == currThread.get()) {
            count++;
            return;
        }
        // 自旋，直到枪锁成功
        long start = System.currentTimeMillis();
        // 获取锁失败，会不断进行空自旋
        while (!currThread.compareAndSet(null, thread)) {
            // 让出当前时间片
            Thread.yield();
        }
        log.info("线程：" + thread.getId() + "拿到锁" + ", 耗时：" + (System.currentTimeMillis() - start) / 1000);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        Thread thread = Thread.currentThread();
        if (thread == currThread.get()) {
            if (count > 0) {
                count--;
                return;
            }
            // 释放锁
            log.info("线程：" + thread.getId() + "释放锁");
            currThread.set(null);
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    public static void main(String[] args) throws Exception{
        Lock lock = new CLHLock();
//                new SpinLock();
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        CountDownLatch latch = new CountDownLatch(10);
        int count = 100000;
        final int size = 10000;
        for (int i = 0; i < 10; i++) {
            threadPool.submit(() -> {
                try {
                    lock.lock();
                    for (int j = 0; j < size; j++) {
                        counter = counter + 1;
                    }
                    // 前面的节点不lock，node就一直得不到释放
                    lock.lock();

                    Thread.sleep(1000);
                    lock.unlock();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                latch.countDown();
            });
        }

        latch.await();

        log.info("counter == " + counter + ", size = " + count);

    }
}
